<template>
  <!-- 计划批次表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              @change="plantChange"
              v-model="formData.plantId"
              :disabled="formData.id != ''"
              placeholder="请选择工厂"
              style="width: 100%"
            >
              <el-option
                v-for="item in plantList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.plantCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划年份" prop="planYear">
            <el-select
              v-model="formData.planYear"
              placeholder="请选择计划年份"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in yearOptions"
                :key="item"
                :value="Number(item)"
                :label="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划月份" prop="planMonth">
            <el-select
              v-model="formData.planMonth"
              placeholder="请选择计划月份"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in monthOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="存货" prop="materialId">
            <select-contentTwo-input
              v-if="!props.isReadonly"
              :width="280"
              :isMultiple="false"
              :showSelectDevice="formData.materialList"
              :plantId="formData.plantId"
              :disabled="formData.id != ''"
              @get-device="(id, object) => getDevice(id, object, $index)"
            />
            <span v-else
              >{{ formData.materialCode }}-{{ formData.materialName }}</span
            >
            <!-- <el-select
              v-if="!props.isReadonly"
              v-model="formData.materialId"
              placeholder="请输入成品存货"
              clearable
              filterable
              @change="changeFinishedMaterial"
              style="width: 100%"
              :disabled="formData.id != ''"
            >
              <el-option
                v-for="item in finishedMaterials"
                :key="item.id"
                :label="`${item.materialCode}-${item.materialName}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{
              `${formData.materialCode}-${formData.materialName}`
            }}</span>
             -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图号" prop="figureNumber">
            <!-- <select-contentTwo-input
              v-if="!props.isReadonly"
              :width="280"
              :isMultiple="false"
              :showSelectDevice="formData.materialList"
              :plantId="formData.plantId"
              :disabled="formData.id != ''"
              @get-device="(id, object) => getDevice(id, object, $index)"
            />
            <span v-else
              >{{ formData.materialCode }}-{{ formData.materialName }}</span
            > -->
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.figureNumber"
              placeholder="请输入图号"
              disabled
              clearable
            />
            <span v-else>{{ `${formData.figureNumber}` }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划批次" prop="planBatch">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planBatch"
              placeholder="请输入计划批次"
              clearable
            />

            <span v-else>{{ formData.planBatch }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="批次数量" prop="planBatchNum">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planBatchNum"
              placeholder="请输入批次数量"
              clearable
            />
            <span v-else>{{ formData.planBatchNum }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已完成数量" prop="planFinishQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.planFinishQuantity"
              placeholder="请输入已完成数量"
              clearable
            />
            <span v-else>{{ formData.planFinishQuantity }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";
import {
  getFirstWorkShopList,
  getMesRouteGroupList,
  getWorkCenterDetail,
  getCurrentYield,
  getFreeDetails,
  getMonthList,
  getYearList,
  getMaterialList,
  getDateshiftCount,
  getOtherWorkShopList,
} from "@/utils/commonData";

import {
  getWeeksInYear,
  getWeekNumber,
  week_date,
  getDaysOfCurrentWeek,
} from "@/utils/dateUtils";
defineOptions({
  name: "MESMESPLANNEDBATCHADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  ceshi: {
    type: Array,
    default: () => {
      return [];
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
const ceshis = ref([]);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    console.log(props.ceshi);

    ceshis.value = props.ceshi;
    console.log(ceshis.value);

    formData.materialId = "";
    formData.materialCode = "";
    formData.materialName = "";
    formData.materialList = [
      {
        id: "",
        materialName: "",
        materialCode: "",
        unit: "",
      },
    ];
    getPlantList();
    plantChange(formData.plantId);
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  materialId: [{ required: true, message: "请选择存货", trigger: "change" }],
  planYear: [{ required: true, message: "请选择计划年", trigger: "change" }],
  planMonth: [{ required: true, message: "请选择计划月份", trigger: "change" }],
  planBatch: [
    { required: true, message: "请输入批次号", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  planBatchNum: [
    { required: true, message: "请输入批次数量", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});
function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else {
    callback();
  }
}

const currentYear = new Date().getFullYear(); // 当前年份
const currentMonth = dayjs().month() + 1; // 当前年份
const currentWeek = getWeekNumber(new Date()); // 当前第几周
const formRef = ref(ElForm);
// 获取年度列表
const yearOptions = ref();
// 获取周列表
// const monthOptions = ref<OptionType[]>();
const weekOptions = ref<OptionType[]>();

// 月份份
const monthOptions = [
  {
    id: 1,
    name: "1月",
  },
  {
    id: 2,
    name: "2月",
  },
  {
    id: 3,
    name: "3月",
  },
  {
    id: 4,
    name: "4月",
  },
  {
    id: 5,
    name: "5月",
  },
  {
    id: 6,
    name: "6月",
  },
  {
    id: 7,
    name: "7月",
  },
  {
    id: 8,
    name: "8月",
  },
  {
    id: 9,
    name: "9月",
  },
  {
    id: 10,
    name: "10月",
  },
  {
    id: 11,
    name: "11月",
  },
  {
    id: 12,
    name: "12月",
  },
];
let formData = reactive({
  id: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  figureNumber: "",
  planBatch: "",
  planBatchNum: "",
  planFinishQuantity: "",
  planYear: currentYear,
  planMonth: currentMonth,
  planState: "0",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  materialList: [
    {
      id: "",
      materialName: "",
      materialCode: "",
      unit: "",
    },
  ],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        figureNumber,
        planBatch,
        planBatchNum,
        planFinishQuantity,
        planYear,
        planMonth,
        planState,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        figureNumber,
        planBatch,
        planBatchNum,
        planFinishQuantity,
        planYear,
        planMonth,
        planState,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });

      formData.materialList = [
        {
          id: newVal.materialId,
          materialName: newVal.materialName,
          materialCode: newVal.materialCode,
          unit: newVal.baseQuantityUnit,
        },
      ];
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.figureNumber = "";
  formData.planBatch = "";
  formData.planBatchNum = "";
  formData.planFinishQuantity = "";
  formData.planYear = currentYear;
  formData.planMonth = currentMonth;
  formData.planState = "0";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.materialList = [
    {
      id: "",
      materialName: "",
      materialCode: "",
      unit: "",
    },
  ];
}

const loading = ref(false);

/** 计划批次保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesplannedbatch/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
  formData.plantId = plantList.value[0].id;
  getFinishedMaterials();
};

const plantChange = (e) => {
  if (e) {
    plantList.value.forEach((item) => {
      if (item.id == e) {
        formData.plantCode = item.organizationCode;
      }
    });
  } else {
    formData.plantCode = "";
  }
};
// 获取选中的数据进行回显并赋值
function getDevice(Ids: string[], Objects: any, index: number) {
  console.log(Objects[0]);
  formData.materialId = Objects[0].id;
  formData.materialCode = Objects[0].materialCode;
  formData.materialName = Objects[0].materialName;
  formData.figureNumber = Objects[0].figureNumber;
}

//成品存货
const finishedMaterials = ref([]);
async function getFinishedMaterials() {
  if (formData.plantId) {
    await request({
      url: "mdm/mdmmaterial/getProductionList",
      method: "post",
      // data: { plantId: formData.plantId, enabled: 1, materialType: 3 },
      data: { plantId: formData.plantId },
    }).then((res) => {
      finishedMaterials.value = res.data;
    });
  }
}
const changeFinishedMaterial = (id: any) => {
  if (id) {
    finishedMaterials.value.forEach((item) => {
      if (item.id === id) {
        formData.materialCode = item.materialCode;
        formData.materialName = item.materialName;
        formData.figureNumber = item.figureNumber;
      }
    });
  } else {
    formData.materialCode = "";
    formData.materialName = "";
    formData.figureNumber = "";
  }
};

// 改变年份
const selectYear = (e) => {
  if (e) {
    searchParam.value = { ...searchParam.value, planWeek: "" };
    weekOptions.value = getMonthList(e);
  } else {
    weekOptions.value = [];
    searchParam.value = { ...searchParam.value, planWeek: "" };
  }
};
// 改变月份份
const selectMonth = (e) => {
  if (e) {
    searchParam.value.planMonth = e;
  } else {
    searchParam.value.planMonth = "";
  }
};

onMounted(async () => {
  getPlantList();
  // 获取年列表
  yearOptions.value = await getYearList();
  console.log(yearOptions.value);

  // 获取周搜索列表
  weekOptions.value = getMonthList(currentYear);
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
